<template>
  <el-form
    :model="formData"
    ref="formRef"
    @submit.prevent
    :rules="formRules"
    label-width="120px"
  >
    <el-form-item label="事项" prop="happenItem">
      <el-input
        type="textarea"
        :rows="2"
        placeholder="请输入内容"
        v-model="formData.happenItem"
        maxlength="500"
        class="width-custom"
      ></el-input>
    </el-form-item>
    <el-form-item label="事项发生时间" prop="happenTimeYear">
      <el-date-picker
        v-model="formData.happenTimeYear"
        alue-format="yyyy-m"
        type="month"
        style="width: 100%"
      >
      </el-date-picker>
    </el-form-item>
    <el-form-item label="承接单位" prop="deptName">
      <el-select
        style="width: 100%"
        popper-class="dept"
        v-model="formData.deptName"
        placeholder="请选择"
        clearable
      >
        <el-option :value="joinDeptList">
          <el-tree
            :data="joinDeptList"
            node-key="id"
            ref="deptTreePartakeRef"
            :props="defaultProps"
            @check-change="handleCheckChangePartake"
            check-on-click-node
            check-strictly
            :expand-on-click-node="false"
          ></el-tree>
        </el-option>
      </el-select>
    </el-form-item>
    <!-- <el-form-item label="资金来源" prop="fundsSource">
      <el-select class="custom-select-width" v-model="formData.fundsSource">
        <el-option
          class="default-option"
          v-for="item in sourceOptions"
          :key="item.key"
          :value="item.key"
          :label="item.value"
        />
      </el-select>
    </el-form-item> -->
    <el-form-item label="经费类别" prop="feeTypeName">
      <el-input v-model="formData.feeTypeName" readonly>
        <template #append>
          <el-button icon="el-icon-search" @click="handleFundType" />
        </template>
      </el-input>
      <!-- <el-select
        v-model="formData.feeTypeName"
        ref="selectTreeRef"
        class="custom-select-width"
      >
        <el-option :value="feeTypeTreeOptions">
          <el-tree
            class="tree-option"
            :data="feeTypeTreeOptions"
            :check-strictly="true"
            show-checkbox
            check-on-click-node
            accordion
            node-key="id"
            ref="treeRef"
            highlight-current
            :props="defaultProps"
            @check-change="handleCheckChange"
            :expand-on-click-node="false"
          >
          </el-tree>
        </el-option>
      </el-select> -->
    </el-form-item>
    <el-form-item label="政府资金" prop="fundsSourceGov">
      <el-input
        type="number"
        v-model.trim="formData.fundsSourceGov"
        class="width-custom"
      >
        <template #append>元</template>
      </el-input>
    </el-form-item>
    <el-form-item label="企业自筹" prop="fundsSourceCompany">
      <el-input
        type="number"
        v-model.trim="formData.fundsSourceCompany"
        class="width-custom"
      >
        <template #append>元</template>
      </el-input>
    </el-form-item>
    <el-form-item label="其他支出" prop="fundsSourceOther">
      <el-input
        type="number"
        v-model.trim="formData.fundsSourceOther"
        class="width-custom"
      >
        <template #append>元</template>
      </el-input>
    </el-form-item>
  </el-form>

  <el-row justify="end">
    <el-button @click="handleSubmit(false)">取 消</el-button>
    <el-button type="primary" @click="handleSubmit(true)">确 定</el-button>
  </el-row>

  <FundsTypeDialogVue
    :isshow="isshow"
    v-if="isshow"
    @emitFundsCheck="emitFundsCheck"
  />
</template>

<script lang="ts">
import { reactive, defineComponent, toRefs, ref, toRef } from "vue";
import { cloneDeep } from "lodash-es";
// @ts-ignore
import { addFeeOtherSpend, updateFeeOtherSpend } from "/@/api/funds";
import { postSysCompanyList } from "/@/api/organization";
import { postDeptList } from "/@/api/dept";

// @ts-ignore
import NotifMessage from "/@/utils/message/notification";

import FundsTypeDialogVue from "./FundsTypeDialog.vue";

// const fundsSourceOptions = [
//   { key: 1, value: "政府资金" },
//   { key: 2, value: "企业自筹" },
//   { key: 3, value: "其他支出" }
// ];

export default defineComponent({
  emits: ["emitSubmit"],
  components: { FundsTypeDialogVue },
  props: {
    mode: {
      type: String,
      require: true,
      default: "add"
    },
    info: {
      type: Object,
      default: () => {}
    }
  },
  setup(props, { emit }) {
    const formRef = ref<HTMLFormElement | null>(null) as any;
    const isshow = ref(false);

    const currentInfo = toRef(props, "info");

    let joinDeptList = ref([]);

    let state = reactive({
      formData: {
        happenItem: "",
        happenTimeYear: "",
        happenTimeMonth: "",
        deptName: "",
        deptCode: "",
        // fundsSource: "",
        feeTypeName: "",
        // spendAmount: ""
        fundsSourceGov: "",
        fundsSourceCompany: "",
        fundsSourceOther: ""
      },
      defaultProps: {
        children: "children",
        label: "deptDescShrt",
        id: "id"
      }
    });

    const formRules = ref({
      happenItem: [{ required: true, message: "请输入事项", trigger: "blur" }],
      happenTimeYear: [
        { required: true, message: "请选择时间", trigger: "blur" }
      ],
      deptName: [
        { required: true, message: "请选择承接单位", trigger: "change" }
      ],
      // fundsSource: [
      //   { required: true, message: "请选择资金来源", trigger: "change" }
      // ],
      feeTypeName: [
        { required: true, message: "请选择经费类别", trigger: "change" }
      ],
      // spendAmount: [
      //   { required: true, message: "请输入经费金额", trigger: "blur" }
      // ]
      fundsSourceGov: [
        { required: true, message: "请输入金额", trigger: "blur" }
      ],
      fundsSourceCompany: [
        { required: true, message: "请输入金额", trigger: "blur" }
      ],
      fundsSourceOther: [
        { required: true, message: "请输入金额", trigger: "blur" }
      ]
    });

    if (props.mode === "edit") {
      const copyCurrentInfo = cloneDeep(currentInfo.value);
      state.formData = copyCurrentInfo;
      state.formData.happenTimeYear = `${copyCurrentInfo.happenTimeYear}-${copyCurrentInfo.happenTimeMonth}`;
    }

    const initDeptList = async () => {
      const { code, data } = await postDeptList({
        pageSize: 0
      });
      let deptList = [];
      if (code === 200) {
        deptList = data.map(item => {
          return {
            id: item.id,
            deptDescShrt: item.deptDescShrt,
            companyLegalName: item.companyLegalName,
            children: item.children
          };
        });
      }
      let companyList = [];
      const res = await postSysCompanyList({
        pageSize: 0
      });
      if (res.code === 200) {
        res.data.list.map(el => {
          companyList.push({
            id: el.id,
            companyLegalName: el.companyLegalName,
            deptDescShrt: el.companyName,
            isEmp: true
          });
        });
      }

      joinDeptList.value = [
        {
          deptDescShrt: "内部单位",
          disabled: true,
          children: deptList,
          id: "0-0"
        },
        {
          deptDescShrt: "外部单位",
          disabled: true,
          children: companyList,
          id: "0-1"
        }
      ];
    };

    const handleCheckChangePartake = (item: any) => {
      state.formData.deptCode = item.id;
      state.formData.deptName = item.deptDescShrt;
    };

    // 确认提交或者取消
    const handleSubmit = async (isSubmit): Promise<void> => {
      if (isSubmit) {
        const isValid = await new Promise(resolve =>
          formRef.value.validate(resolve)
        );
        if (!isValid) return;

        const newForm = cloneDeep(state.formData);
        const year = formaterDateYear(newForm.happenTimeYear);
        const month = Number(formaterDateMonth(newForm.happenTimeYear));

        newForm.happenTimeYear = year;
        newForm.happenTimeMonth = month;

        if (props.mode === "edit") {
          const { code, message } = await updateFeeOtherSpend(newForm);
          requestSuccess(code, message, isSubmit);
        } else {
          const { code, message } = await addFeeOtherSpend(newForm);
          requestSuccess(code, message, isSubmit);
        }
      } else {
        emit("emitSubmit", isSubmit);
      }
    };

    const formaterDateYear = val => {
      const dt = new Date(val);
      const y = dt.getFullYear();
      return y;
    };

    const formaterDateMonth = val => {
      const dt = new Date(val);
      const m = (dt.getMonth() + 1 + "").padStart(2, "0");
      return m;
    };

    const handleFundType = () => {
      isshow.value = true;
    };

    const emitFundsCheck = val => {
      if (val) {
        state.formData.feeTypeName = val;
      }
      isshow.value = false;
    };

    // 统一处理请求结果方法
    const requestSuccess = (
      code: number,
      message: string,
      isSubmit: boolean
    ) => {
      if (code === 200) {
        NotifMessage.success(message);
        emit("emitSubmit", isSubmit);
      }
    };

    initDeptList();

    return {
      ...toRefs(state),
      isshow,
      formRef,
      formRules,
      joinDeptList,
      handleSubmit,
      handleFundType,
      emitFundsCheck,
      handleCheckChangePartake
    };
  }
});
</script>
<style lang="scss" scoped>
.custom-select-width {
  width: 100% !important;
}

.el-select-dropdown__item {
  height: auto;
  // min-height: 100px;
  // max-height: 274px;
  padding: 0;
  overflow-x: hidden;
  overflow-y: hidden;
}
.el-select-dropdown_item.selected {
  font-weight: normal;
}

.el-select-dropdown_item.selected {
  font-weight: normal;
}

// .tree-option
.tree-option :deep .el-tree-node__content {
  height: auto;
  padding: 0 10px;
}
// .tree-option :deep .el-select-dropdown__list {
//   padding: 0 6px;
// }
.tree-option :deep .el-tree-node__label {
  font-weight: normal;
  padding: 0 10px;
  margin-right: 10px;
}

.el-tree :deep .is-current .el-tree-node__label {
  color: #409eff;
  font-weight: 700;
}
.el-tree :deep .is-current .el-tree-node__children .el-tree-node__label {
  color: #606266;
  font-weight: normal;
}
.default-option :deep .el-tree-node__label {
  font-weight: normal;
  padding: 0 10px;
  // margin-right: 10px;
}

.default-option {
  padding: 0 10px !important;
}
</style>
